package com.nwpu.intimacy.friend;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.nwpu.intimacy.R;
import com.nwpu.intimacy.main.MainActivity;
import com.nwpu.intimacy.utils.CacheUtil;

public class ResponseMessageActivity extends Activity {

	private static final String URL = "http://10.128.51.203:8080/SoftwareEngineer/addUser";

	private final static int USER_RESPONSE_SUCCESS = 0x114;

	private ImageView user_image_my;
	private TextView user_name_friend;
	private ImageView qrCode_user;

	private TextView sex;
	private TextView homeTown;
	private TextView comment;

	private Button agreeButton;
	private Button refuseButton;

	private static String str1;
	private static String str2;
	private static String str3;
	private static String str4;
	private static Bitmap bitmap;

	private SharedPreferences sp_userMessage;

	private Handler responseHandler;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_responseaddfriend);

		getActionBar().hide();

		sp_userMessage = this.getSharedPreferences("userMessage",
				Context.MODE_PRIVATE);

		initLayout();
		initMessage();

		agreeButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				responseRequest("true");

			}
		});

		refuseButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				responseRequest("false");

			}
		});

		// 线程交互
		responseHandler = new Handler() {

			@SuppressLint("NewApi")
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case USER_RESPONSE_SUCCESS: {
					// 跳转界面 登录成功

					try {

						if (msg.obj.toString().equals("true")) {

							String friend_str = CacheUtil.getFromFile(
									"friendsInformation", "Friend");

							JSONArray jsonArray_friend = new JSONArray(
									friend_str);
							JSONObject jsonObject_friend = new JSONObject();

							jsonObject_friend.put("username", user_name_friend
									.getText().toString());
							jsonObject_friend.put("area", sex.getText()
									.toString());
							jsonObject_friend.put("signature", homeTown
									.getText().toString());
							jsonObject_friend.put("sex", comment.getText()
									.toString());

							jsonArray_friend.put(jsonObject_friend);

							CacheUtil.WriteToFile(user_name_friend.getText()
									.toString(), bitmap, "FriendPhoto");

							CacheUtil.writeToFile(jsonArray_friend.toString(),
									"friendsInformation", "Friend");

						}
						String str = CacheUtil.getFromFile(
								sp_userMessage.getString("USER_NAME", "")
										+ "requestFriend", "Request");

						JSONArray jsonArray_file = new JSONArray(str);
						JSONArray jsonArray_new = new JSONArray();
						for (int i = 0; i < jsonArray_file.length(); i++) {

							JSONObject jsonObject = (JSONObject) jsonArray_file
									.get(i);

							if (!user_name_friend.getText().toString()
									.equals(jsonObject.optString("username"))) {

								jsonArray_new.put(jsonObject);

							}

						}

						CacheUtil.writeToFile(jsonArray_new.toString(),
								sp_userMessage.getString("USER_NAME", "")
										+ "requestFriend", "Request");

						setResult(Activity.RESULT_OK);
						Intent intent = new Intent();
						intent.setClass(getApplicationContext(),
								MainActivity.class);
						intent.putExtra("setPosition", 1);
						startActivity(intent);

						finish();

					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					break;
				}
				default:
					super.handleMessage(msg);
				}
			}

		};

	}

	/**
	 * 初始化控件
	 */
	public void initLayout() {

		user_name_friend = (TextView) findViewById(R.id.user_name_my);
		qrCode_user = (ImageView) findViewById(R.id.qrCode_user);
		user_image_my = (ImageView) findViewById(R.id.user_image_my);

		sex = (TextView) findViewById(R.id.sex_responseinformation);
		homeTown = (TextView) findViewById(R.id.hometown_responseinformation);
		comment = (TextView) findViewById(R.id.comment_responseinformation);

		agreeButton = (Button) findViewById(R.id.agree_response);
		refuseButton = (Button) findViewById(R.id.refuse_response);

	}

	/**
	 * 静态方法，其他Activity跳转时调用
	 * 
	 * @param str1
	 * @param str2
	 * @param str3
	 * @param str4
	 * @param bitmap
	 */
	public static void initInformation(String str1, String str2, String str3,
			String str4, Bitmap bitmap) {

		ResponseMessageActivity.str1 = str1;
		ResponseMessageActivity.str2 = str2;
		ResponseMessageActivity.str3 = str3;
		ResponseMessageActivity.str4 = str4;
		ResponseMessageActivity.bitmap = bitmap;

	}

	/**
	 * 初始化界面内容
	 * 
	 * @param str1
	 * @param str2
	 * @param str3
	 * @param str4
	 * @param str5
	 */
	public void initMessage() {

		qrCode_user.setVisibility(View.GONE);
		user_name_friend.setText(str1);
		sex.setText(str2);
		homeTown.setText(str3);
		comment.setText(str4);

		Drawable drawable = new BitmapDrawable(bitmap);

		user_image_my.setImageDrawable(drawable);

	}

	public void responseRequest(final String isResponse) {

		new Thread() {

			public void run() {

				try {

					// 封装用户信息
					JSONArray jsonArray = new JSONArray();
					JSONObject jsonObject = new JSONObject();

					jsonObject.put("friendname", user_name_friend.getText()
							.toString());
					jsonObject.put("hostname",
							sp_userMessage.getString("USER_NAME", ""));
					jsonObject.put("status", 3);
					jsonObject.put("content", isResponse);

					jsonArray.put(jsonObject);

					HttpClient client = new DefaultHttpClient();

					Log.e("login data", jsonArray.toString());

					HttpPost httpPost = new HttpPost(URL);

					// 设置参数，仿html表单提交
					List<NameValuePair> paramList = new ArrayList<NameValuePair>();
					BasicNameValuePair param = new BasicNameValuePair(
							"addUser", jsonArray + "");
					paramList.add(param);

					httpPost.setEntity(new UrlEncodedFormEntity(paramList,
							"UTF_8"));

					HttpResponse httpResponse = client.execute(httpPost);

					String result = EntityUtils.toString(
							httpResponse.getEntity(), HTTP.UTF_8);

					Message msg = new Message();
					msg.what = USER_RESPONSE_SUCCESS;
					msg.obj = isResponse;
					responseHandler.sendMessage(msg);

				} catch (JSONException e) {
					e.printStackTrace();
				} catch (MalformedURLException e1) {
					e1.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}.start();

	}

}
